# encoding:utf-8
import json

from django.contrib.auth import logout
from django.contrib.auth.hashers import check_password
from django.http import JsonResponse
from django.shortcuts import render, redirect
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

# Create your views here.
from common.API import res_josn_data
from common.API.auth import add_auth_session, login_required
from common.API.captcha import make_captcha
from common.API.echarts import echarts_pie, json_response
from common.API.log import login_log
from login.models import Logo, LoginLog, ExecLog
from system_manage.models import User, Role, Power, RolePower, Department


def index(request):
    if request.method == 'GET':
        return redirect('/login')


def home(request):
    if request.method == 'GET':
        return render(request, 'login/home.html')


def login(request):
    if request.method == 'GET':
        return render(request, 'login/login.html')
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get("password")
        code = request.POST.get('captcha')
        s_code = request.session.get("code")
        print('验证码:', code, s_code)

        request.session["code"] = None

        if code != s_code:
            login_log(request, uid=username, is_access=False, desc='验证码错误')
            return res_josn_data.fail_api(msg="验证码错误")

        user = User.objects.get(id_number=username)
        if user is None:
            login_log(request, username, is_access=False, desc='用户不存在')
            return res_josn_data.fail_api('用户名不正确')

        password_valid = check_password(password, user.id_password)

        if password_valid:
            print(user.id_number, user.user_name)
            refresh = TokenObtainPairSerializer.get_token(user)
            data = {"userId": user.id_number, "token": str(refresh.access_token), "refresh": str(refresh),
                    "username": user.user_name}
            request.user = user
            request.session["role_id"] = user.role_id  # 通过session的role_id获取用户对应的菜单及权限
            request.session["user_id"] = user.id_number  # 写入日志时需要用到

            add_auth_session(request)  # 权限存入 session['permissions']
            login_log(request, username, is_access=True, desc='登陆成功')
            print('data:', data)
            return res_josn_data.table_success(data=data)
        else:
            login_log(request, username, is_access=False, desc='密码错误')
            return res_josn_data.fail_api(msg="密码错误")


def get_captcha(request):
    return make_captcha(request)


def login_in(request):
    user_id = request.session.get('user_id')
    if user_id:
        return render(request, "login/index.html", {'user_id': user_id})


def login_out(request):
    user_id = request.session.get('user_id')
    login_log(request, uid=user_id, is_access=True, desc='退出登录')
    logout(request)
    request.user = None
    return redirect('/login')


def web_menu(request):
    home_info = Logo.objects.filter(type='0').first()
    logo_info = Logo.objects.filter(type='1').first()
    title_info = Logo.objects.filter(type='2').first()
    menu_info = Power.objects.filter(type=1).order_by('sort')  # 目录
    # 查询权限ID
    role_id = request.session.get('role_id')
    menu_id = RolePower.objects.values_list('power_id').filter(role_id=role_id)
    permission_id = [i[0] for i in menu_id]
    print(f'当前用户权限ID:{permission_id}')

    menu_data = {
        "homeInfo": {
            "title": f"{home_info.name}",
            "href": f"{home_info.url}"
        },
        "logoInfo": {
            "title": f"{logo_info.name}",
            "image": f"{logo_info.icon}",
            "href": f"{logo_info.url}"
        },
        "menuInfo": [
            {
                "title": f"{title_info.name}",
                "icon": f"{title_info.icon}",
                "href": f"{title_info.url}",
                "target": "_self",
                "child": []
            }
        ]
    }
    for item in menu_info:
        if item.id in permission_id:
            menu_data["menuInfo"][0]["child"].append({
                "title": f"{item.name}",
                "icon": f"{item.icon}",
                "href": f"{item.code}",
                "target": "_self",
                "child": []
            })
            # 查询子菜单
            sub_menu_info = Power.objects.filter(parent_id=item.id).order_by('sort')
            for sub_item in sub_menu_info:
                if sub_item.id in permission_id:
                    menu_data["menuInfo"][0]["child"][-1]["child"].append({
                        "title": f"{sub_item.name}",
                        "icon": f"{sub_item.icon}",
                        "href": f"{sub_item.code}",
                        "target": "_self"
                    })
    print(menu_data)
    return JsonResponse(menu_data, safe=False)


def echarts(request):
    if request.method == 'POST':
        n_type = ['用户', '部门', '角色', '权限', '登陆日志', '操作日志']
        data_list = [User.objects.count(), Department.objects.count(), Role.objects.count(), Power.objects.count(), LoginLog.objects.count(), ExecLog.objects.count()]
        title = '1.数量统计'
        c = echarts_pie(n_type, data_list, title)
        return json_response(json.loads(c))

